package com.kye.express.business.online_pay.detail;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.databinding.FragmentOnlinePayDetailBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.online.GetPayRecordDetailsResultBean;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 支付详情
 */
public class OnlinePayDetailFragment extends BaseAppCompatFragment implements OnlinePayDetailFragmentContract.OnlinePayDetailFragmentView {
    private static final String ARG_DATA = "data";
    private static final String ARG_IS_PAY_RESULT = "is_pay_result";
    private FragmentOnlinePayDetailBinding mBinding;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private OnlinePayDetailListener mListener = null;
    private String mWaybill = "";
    private boolean mIsPayResult = false;//是否是支付成功后跳转的页面
    private Dialog mLoadingDialog;
    private OnlinePayDetailFragmentContract.OnlinePayDetailFragmentViewPresenter mPresendter;

    private List<GetPayRecordDetailsResultBean.PayDtlBean> mSourceCodeDataBeans;
    private List<GetPayRecordDetailsResultBean.PayDtlBean.ReceivDtlBean> mWaybillNoDataBeans;

    public static OnlinePayDetailFragment newInstance(String waybill, boolean isPayResult) {
        OnlinePayDetailFragment fragment = new OnlinePayDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_DATA, waybill);
        bundle.putBoolean(ARG_IS_PAY_RESULT, isPayResult);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mListener = (context instanceof OnlinePayDetailListener) ? (OnlinePayDetailListener) context : null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_online_pay_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = FragmentOnlinePayDetailBinding.bind(view);
        mPresendter = new OnlinePayDetailFragmentContract.OnlinePayDetailFragmentViewPresenter(getActivity());
        mPresendter.bind(this);
        initView();
        initEvent();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresendter.unbind();
    }

    private void initView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mWaybill = bundle.getString(ARG_DATA);
            mIsPayResult = bundle.getBoolean(ARG_IS_PAY_RESULT, false);
        }
        if (mIsPayResult) {
            getActivity().setTitle("");
            mBinding.llDetailHead.setVisibility(View.GONE);
            mBinding.llPayResultHead.setVisibility(View.VISIBLE);
        } else {
            getActivity().setTitle(getString(R.string.online_pay_detail));
            mBinding.llDetailHead.setVisibility(View.VISIBLE);
            mBinding.llPayResultHead.setVisibility(View.GONE);
        }
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(GetPayRecordDetailsResultBean.PayDtlBean.class, new OnlinePayDetailtemViewBinder(getActivity()));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        RecyclerViewDivider.with(getActivity())
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(getActivity(), 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mPresendter.getPayDetail(mWaybill);
    }

    private void initEvent() {
        RxView.clicks(mBinding.superTextWaybillCount)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mListener != null && mWaybillNoDataBeans != null && mWaybillNoDataBeans.size() > 0) {
                            mListener.onOpenWaybillList(mWaybillNoDataBeans);
                        }
                    }
                });
    }

    @Override
    public void onComplete() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(GetPayRecordDetailsResultBean datas) {
        if (datas != null) {
            mSourceCodeDataBeans = datas.getPayDtl();
            if (mSourceCodeDataBeans != null && mSourceCodeDataBeans.size() > 0) {
                mDatas.clear();
                mDatas.addAll(mSourceCodeDataBeans);
                mAdapter.notifyDataSetChanged();

                mWaybillNoDataBeans = mSourceCodeDataBeans.get(0).getReceivDtl();
            }

            if (mWaybillNoDataBeans != null) {
                mBinding.superTextWaybillCount.setLeftTopString(String.format(getString(R.string.invoice_online_waybill_title), mWaybillNoDataBeans.size()));
                StringBuilder stringBuilder = new StringBuilder();
                for (GetPayRecordDetailsResultBean.PayDtlBean.ReceivDtlBean item : mWaybillNoDataBeans) {
                    stringBuilder.append(item.getWaybill()).append("、");
                }
                if (stringBuilder.length() > 0) {
                    String waybills = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
                    mBinding.superTextWaybillCount.setLeftBottomString(waybills);
                }
            }
        }
    }

    @Override
    public void onApiError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onOtherError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}
